// utils/router.js
// 路由管理工具

const { isNewUser, getLoginStatus } = require('./auth.js')
const { shouldSkipAuthentication } = require('./config.js')

/**
 * 路由守卫 - 检查页面访问权限
 */
const routeGuard = (targetRoute) => {
  // 如果跳过认证，允许所有页面访问
  if (shouldSkipAuthentication()) {
    console.warn('🚫 认证已屏蔽，允许所有页面访问:', targetRoute)
    return { allowed: true }
  }
  
  const app = getApp()
  const isLoggedIn = app ? app.getLoginStatus() : false
  
  // 公开页面，无需登录
  const publicRoutes = [
    'pages/login/login',
    'pages/phone-verify/phone-verify'
  ]
  
  // 需要登录的页面
  const authRequiredRoutes = [
    'pages/index/index',
    'pages/discovery/discovery',
    'pages/matches/matches',
    'pages/messages/messages',
    'pages/profile/profile',
    'pages/user-center/user-center',
    'pages/community/community',
    'pages/avatar/avatar'
  ]
  
  // 如果是公开页面，直接允许访问
  if (publicRoutes.includes(targetRoute)) {
    return { allowed: true }
  }
  
  // 如果需要登录但未登录，重定向到登录页
  if (authRequiredRoutes.includes(targetRoute) && !isLoggedIn) {
    return {
      allowed: false,
      redirect: '/pages/login/login'
    }
  }
  
  // 如果已登录但是新用户，且不在头像创建页，重定向到头像创建
  if (isLoggedIn && isNewUser() && targetRoute !== 'pages/avatar/avatar') {
    return {
      allowed: false,
      redirect: '/pages/avatar/avatar'
    }
  }
  
  return { allowed: true }
}

/**
 * 安全导航 - 带权限检查的页面跳转
 */
const navigateTo = (url, options = {}) => {
  const route = url.split('?')[0].replace('/', '')
  const guard = routeGuard(route)
  
  if (!guard.allowed && guard.redirect) {
    wx.reLaunch({
      url: guard.redirect
    })
    return Promise.reject(new Error('权限不足，已重定向'))
  }
  
  return new Promise((resolve, reject) => {
    wx.navigateTo({
      url,
      ...options,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 安全重定向
 */
const redirectTo = (url, options = {}) => {
  const route = url.split('?')[0].replace('/', '')
  const guard = routeGuard(route)
  
  if (!guard.allowed && guard.redirect) {
    wx.reLaunch({
      url: guard.redirect
    })
    return Promise.reject(new Error('权限不足，已重定向'))
  }
  
  return new Promise((resolve, reject) => {
    wx.redirectTo({
      url,
      ...options,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 安全Tab切换
 */
const switchTab = (url, options = {}) => {
  const route = url.split('?')[0].replace('/', '')
  const guard = routeGuard(route)
  
  if (!guard.allowed && guard.redirect) {
    wx.reLaunch({
      url: guard.redirect
    })
    return Promise.reject(new Error('权限不足，已重定向'))
  }
  
  return new Promise((resolve, reject) => {
    wx.switchTab({
      url,
      ...options,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 重新启动应用
 */
const reLaunch = (url, options = {}) => {
  return new Promise((resolve, reject) => {
    wx.reLaunch({
      url,
      ...options,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 返回上一页
 */
const navigateBack = (options = {}) => {
  return new Promise((resolve, reject) => {
    wx.navigateBack({
      ...options,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 获取当前页面路径
 */
const getCurrentRoute = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage ? currentPage.route : ''
}

/**
 * 获取页面栈信息
 */
const getPageStack = () => {
  const pages = getCurrentPages()
  return pages.map(page => ({
    route: page.route,
    options: page.options
  }))
}

/**
 * 登录后重定向逻辑
 */
const redirectAfterLogin = () => {
  if (isNewUser()) {
    // 新用户，跳转到头像创建页
    reLaunch('/pages/avatar/avatar')
  } else {
    // 老用户，跳转到首页
    switchTab('/pages/index/index')
  }
}

/**
 * 退出登录后重定向
 */
const redirectAfterLogout = () => {
  reLaunch('/pages/login/login')
}

module.exports = {
  routeGuard,
  navigateTo,
  redirectTo,
  switchTab,
  reLaunch,
  navigateBack,
  getCurrentRoute,
  getPageStack,
  redirectAfterLogin,
  redirectAfterLogout
}